// Author  : Morbid
// Time    : 2022/04/30 20:07
// FileName: Main_67.java
// Software: IntelliJ IDEA

package LeetCode;

public class Main_67 {
    //67. 二进制求和
    static String addBinary(String a, String b) {
        int len = Math.max(a.length(), b.length());
        int lenDiff = a.length() - b.length();
        String[] str1;
        String[] str2;
        if (lenDiff > 0) {
            str1 = a.trim().split("");
            str2 = getArr(len, lenDiff, b);
        } else if (lenDiff < 0) {
            str1 = getArr(len, -lenDiff, a);
            str2 = b.trim().split("");
        } else {
            str1 = a.trim().split("");
            str2 = b.trim().split("");
        }
        int cy = 0;
        String[] add = new String[len + 1];
        for (int i = len - 1; i >= 0; i--) {
            int tem = Integer.parseInt(str1[i]) + Integer.parseInt(str2[i]) + cy;
            if (tem == 0) {
                add[i + 1] = "0";
                cy = 0;
            }
            if (tem == 1) {
                add[i + 1] = "1";
                cy = 0;
            }
            if (tem == 2) {
                add[i + 1] = "0";
                cy = 1;
            }
            if (tem == 3) {
                add[i + 1] = "1";
                cy = 1;
            }
        }
        if (cy == 1) {
            add[0] = "1";
            return toString(add);
        } else {
            String[] add1 = new String[len];
            System.arraycopy(add, 1, add1, 0, len);
            return toString(add1);
        }
    }

    //将String转为String[]
    static String[] getArr(int len, int lenDiff, String a) {
        String[] str1 = new String[len];
        for (int i = 0; i < lenDiff; i++)
            str1[i] = "0";
        String[] tem = a.trim().split("");
        System.arraycopy(tem, 0, str1, lenDiff, tem.length);
        return str1;
    }

    //将String[]转为String
    static String toString(String[] arr) {
        StringBuilder str = new StringBuilder();
        for (String s : arr) {
            str.append(s);
        }
        return String.valueOf(str);
    }

    public static void main(String[] args) {
        String a = "1010", b = "1011";
        System.out.println(addBinary(a, b));
    }

}
